
<template>
  <!-- 模板内容保持不变，仅移除el-table的border属性 -->
  <div class="home">
    <!-- 合并的统计信息和表格卡片 -->
    <el-card class="stats-table-card" shadow="never">
      <template #header>
        <div class="table-header">
          <div class="header">
            <div class="brand">EasyTool</div>
            <div class="scrape-controls">
              <el-button type="primary" size="large" :loading="eventsLoading" @click="handleRefreshEvents">
                <el-icon>
                  <Refresh />
                </el-icon>
                刷新赛事
              </el-button>
              <el-date-picker
                v-model="selectedDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                size="large"
                style="width: 200px"
                :disabled-date="disabledDate"
                :key="datePickerKey"
                @change="handleDateChange"
              />
              <el-select v-model="selectedEventId" placeholder="选择比赛" filterable clearable :loading="eventsLoading"
                size="large" style="width: 400px" @change="handleEventChange">
                <el-option v-for="evt in eventList" :key="evt.id"
                  :label="`${evt.league} ${evt.tname1} VS ${evt.tname2}`" :value="evt.pid">
                  <span style="color: red;">{{ evt.league }}</span> {{ evt.tname1 }} VS {{ evt.tname2 }}
                </el-option>
              </el-select>
              <el-select v-model="selectedFirstScoreId" filterable clearable :loading="companiesLoading"
                    loading-text="加载中..." no-data-text="暂无数据" no-match-text="无匹配项" style="width: 170px"
                    @change="handleFirstScoreChange">
                    <el-option v-for="company in firstScore" :key="company.id" :label="company.firstScore"
                      :value="company.id" />
                  </el-select>

              <el-button type="primary" size="large" :loading="scrapeLoading" @click="handleScrape">开始爬取</el-button>
            </div>
            <div class="user-actions">
              <el-dropdown>
                <el-avatar size="large" class="user-avatar">
                  <img src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
                </el-avatar>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="openChangePasswordDialog">修改密码</el-dropdown-item>
                    <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </template>

      <!-- 统计信息区域 -->
      <div class="stats-section">
        <div class="stats-table-wrapper">
          <!-- 分组表头 -->
          <div class="group-headers">
            <div class="group-header empty-header">
              <div class="header-controls">
                <div class="companies-info">
                  <span>所选公司：</span>
                  <el-select v-model="selectedCompanyId" filterable clearable :loading="companiesLoading"
                    loading-text="加载中..." no-data-text="暂无数据" no-match-text="无匹配项" style="width: 170px"
                    @change="handleCompanyChange">
                    <el-option v-for="company in companies" :key="company.cid" :label="company.cname"
                      :value="company.cid" />
                  </el-select>
                </div>

              </div>
            </div>
            <div class="group-header index-header">
              <span>指数</span>
            </div>
            <div class="group-header total-header">
              <span>总计</span>
            </div>
          </div>
          <!-- 数据表格 -->
          <el-table :data="statsData" border class="stats-table" :show-header="true" size="small" :fit="false">
            <!-- 复选框和行标题列 -->
            <el-table-column width="180px" align="center">
              <template #header>
                <span></span>
              </template>
              <template #default="{ row }">
                <div style="display: flex; align-items: center; justify-content: center; gap: 8px;">
                  <el-checkbox v-model="row.selected" @change="handleRowSelectionChange(row)" />
                  <div :class="['category-label', row.type]">
                    {{ row.category }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <!-- 指数部分 -->
            <el-table-column prop="homeOdds" label="主队" width="80" align="center" />
            <el-table-column prop="handicap" label="盘口" width="100" align="center" />
            <el-table-column prop="awayOdds" label="客队" width="80" align="center" />
            <!-- 总计部分 -->
            <el-table-column prop="totalGames" label="场" width="80" align="center">
              <template #default="{ row }">
                <div class="clickable-cell" @click="handleStatsClick(row, 'total')">
                  {{ row.totalGames }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="homeWins" label="主" width="80" align="center">
              <template #default="{ row }">
                <div class="clickable-cell" @click="handleStatsClick(row, 'home')">
                  {{ row.homeWins }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="draws" label="和" width="80" align="center">
              <template #default="{ row }">
                <div class="clickable-cell" @click="handleStatsClick(row, 'draw')">
                  {{ row.draws }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="awayWins" label="客" width="80" align="center">
              <template #default="{ row }">
                <div class="clickable-cell" @click="handleStatsClick(row, 'away')">
                  {{ row.awayWins }}
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 表格区域：移除border属性，解决灰色线条问题 -->
      <el-table :data="pagedData" height="560" stripe border>
        <el-table-column prop="league" label="赛事" width="120" show-overflow-tooltip align="center" />
        <el-table-column prop="midtime" label="比赛时间" width="120" show-overflow-tooltip align="center" />
        <el-table-column prop="match" label="对阵双方" min-width="140" show-overflow-tooltip  align="center" />
        <el-table-column prop="score" width="120" align="center">
          <template #header>
            <div class="header-with-filter">
              <div class="header-title">终场/上半场</div>
              <el-select v-model="filters.score" placeholder="筛选" size="small" clearable filterable
                style="width: 100px; margin-top: 4px;" @change="handleFilterChange">
                <el-option label="0:0" value="0:0" />
                <el-option label="0:1" value="0:1" />
                <el-option label="0:2" value="0:2" />
                <el-option label="0:3" value="0:3" />
                <el-option label="1:0" value="1:0" />
                <el-option label="1:1" value="1:1" />
                <el-option label="1:2" value="1:2" />
                <el-option label="1:3" value="1:3" />
                <el-option label="2:0" value="2:0" />
                <el-option label="2:1" value="2:1" />
                <el-option label="2:2" value="2:2" />
                <el-option label="3:0" value="3:0" />
                <el-option label="3:1" value="3:1" />
              </el-select>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="goalTime" label="进球时间" width="110" align="center" />
        <el-table-column prop="early" min-width="140" show-overflow-tooltip align="center">
          <template #header>
            <div class="header-with-filter">
              <div class="header-title">早盘</div>
              <el-select v-model="filters.morning_session" placeholder="筛选" size="small" clearable filterable
                style="width: 120px; margin-top: 4px;" @change="handleFilterChange">
                <el-option label="平手" value="平手" />
                <el-option label="平手/半球" value="平手/半球" />
                <el-option label="半球" value="半球" />
                <el-option label="半球/一球" value="半球/一球" />
                <el-option label="一球" value="一球" />
                <el-option label="一球/球半" value="一球/球半" />
                <el-option label="球半" value="球半" />
                <el-option label="球半/两球" value="球半/两球" />
                <el-option label="受让平手/半球" value="受让平手/半球" />
                <el-option label="受让半球" value="受让半球" />
                <el-option label="受让半球/一球" value="受让半球/一球" />
                <el-option label="受让一球" value="受让一球" />
                <el-option label="受让一球/球半" value="受让一球/球半" />
                <el-option label="受让球半" value="受让球半" />
                <el-option label="受让球半/两球" value="受让球半/两球" />
              </el-select>
            </div>
          </template>
          <template #default="{ row }">
            <el-link type="primary" :underline="false" @click="openDetail(row)">
              <span v-html="highlightShouRang(row.early)"></span>
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="final" min-width="140" show-overflow-tooltip align="center">
          <template #header>
            <div class="header-with-filter">
              <div class="header-title">终盘</div>
              <el-select v-model="filters.closing_session" placeholder="筛选" size="small" clearable filterable
                style="width: 100px; margin-top: 4px;" @change="handleFilterChange">
                <el-option label="平手" value="平手" />
                <el-option label="平手/半球" value="平手/半球" />
                <el-option label="半球" value="半球" />
                <el-option label="半球/一球" value="半球/一球" />
                <el-option label="一球" value="一球" />
                <el-option label="一球/球半" value="一球/球半" />
                <el-option label="球半" value="球半" />
                <el-option label="球半/两球" value="球半/两球" />
                <el-option label="受让平手/半球" value="受让平手/半球" />
                <el-option label="受让半球" value="受让半球" />
                <el-option label="受让半球/一球" value="受让半球/一球" />
                <el-option label="受让一球" value="受让一球" />
                <el-option label="受让一球/球半" value="受让一球/球半" />
                <el-option label="受让球半" value="受让球半" />
                <el-option label="受让球半/两球" value="受让球半/两球" />
              </el-select>
            </div>
          </template>
          <template #default="{ row }">
            <el-link type="primary" :underline="false" @click="openDetail(row)">
              <span v-html="highlightShouRang(row.final)"></span>
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="midHandicap" min-width="160" show-overflow-tooltip align="center">
          <template #header>
            <div class="header-with-filter">
              <div class="header-title">中场让球盘</div>
              <el-select v-model="filters.midfield" placeholder="筛选" size="small" clearable filterable
                style="width: 120px; margin-top: 4px;" @change="handleFilterChange">
                <el-option label="平手" value="平手" />
                <el-option label="平手/半球" value="平手/半球" />
                <el-option label="半球" value="半球" />
                <el-option label="半球/一球" value="半球/一球" />
                <el-option label="一球" value="一球" />
                <el-option label="一球/球半" value="一球/球半" />
                <el-option label="球半" value="球半" />
                <el-option label="球半/两球" value="球半/两球" />
                <el-option label="受让平手/半球" value="受让平手/半球" />
                <el-option label="受让半球" value="受让半球" />
                <el-option label="受让半球/一球" value="受让半球/一球" />
                <el-option label="受让一球" value="受让一球" />
                <el-option label="受让一球/球半" value="受让一球/球半" />
                <el-option label="受让球半" value="受让球半" />
                <el-option label="受让球半/两球" value="受让球半/两球" />
              </el-select>
            </div>
          </template>
          <template #default="{ row }">
            <el-link type="primary" :underline="false" @click="openDetail(row)">{{ row.midHandicap }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="overunder" width="140" align="center">
          <template #header>
            <div class="header-with-filter">
              <div class="header-title">大小盘</div>
              <el-select v-model="filters.big_small_plate" placeholder="筛选" size="small" clearable filterable
                style="width: 80px; margin-top: 4px;" @change="handleFilterChange">
                <el-option label="2" value="2" />
                <el-option label="2/2.5" value="2/2.5" />
                <el-option label="2.5" value="2.5" />
                <el-option label="2.5/3" value="2.5/3" />
                <el-option label="3" value="3" />
                <el-option label="3/3.5" value="3/3.5" />
                <el-option label="3.5" value="3.5" />
                <el-option label="3.5/4" value="3.5/4" />
                <el-option label="4" value="4" />
              </el-select>
            </div>
          </template>
          <template #default="{ row }">
            <el-link type="primary" :underline="false" @click="openDetail2(row)">
              {{ row.overunder }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="midOverunder" width="140" align="center">
          <template #header>
            <div class="header-with-filter">
              <div class="header-title">中场大小盘</div>
              <el-select v-model="filters.mid_big_small_plate" placeholder="筛选" size="small" clearable filterable
                style="width: 90px; margin-top: 4px;" @change="handleFilterChange">
                <el-option label="1" value="1" />
                <el-option label="1/1.5" value="1/1.5" />
                <el-option label="1.5" value="1.5" />
                <el-option label="1.5/2" value="1.5/2" />
                <el-option label="2" value="2" />
                <el-option label="2/2.5" value="2/2.5" />
                <el-option label="2.5" value="2.5" />
                <el-option label="2.5/3" value="2.5/3" />
                <el-option label="3" value="3" />
                <el-option label="3/3.5" value="3/3.5" />
                <el-option label="3.5" value="3.5" />
                <el-option label="3.5/4" value="3.5/4" />
                <el-option label="4" value="4" />
                <el-option label="4/4.5" value="4/4.5" />
                <el-option label="4.5" value="4.5" />
                <el-option label="4.5/5" value="4.5/5" />
                <el-option label="5" value="5" />
                <el-option label="5/5.5" value="5/5.5" />
                <el-option label="5.5" value="5.5" />
                <el-option label="5.5/6" value="5.5/6" />
                <el-option label="6" value="6" />
              </el-select>
            </div>
          </template>
          <template #default="{ row }">
            <el-link type="primary" :underline="false" @click="openDetail2(row)">
              {{ row.midOverunder }}
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="pager">
        <div class="total">共 {{ useServerPaging ? totalCount : filteredData.length }} 条</div>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[20, 50, 100]"
          layout="sizes, prev, pager, next, jumper" :total="useServerPaging ? totalCount : filteredData.length"
          background @current-change="onPageChange" @size-change="onPageSizeChange" prev-text="上一页" next-text="下一页"
          jumper-text="跳至" />
      </div>
    </el-card>
    <!-- 修改密码对话框 -->
    <el-dialog v-model="changePasswordVisible" title="修改密码" width="400px" :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form ref="changePasswordFormRef" :model="changePasswordForm" :rules="changePasswordRules" label-width="100px"
        size="large">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="changePasswordForm.newPassword" type="password" placeholder="请输入新密码" show-password
            clearable />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="changePasswordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password
            clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelChangePassword">取消</el-button>
          <el-button type="primary" @click="handleChangePassword" :loading="changePasswordLoading">
            {{ changePasswordLoading ? '修改中...' : '确认修改' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 数据爬取进度对话框 -->
    <el-dialog v-model="scrapeDialogVisible" title="数据爬取" width="300px" :close-on-click-modal="false"
      :close-on-press-escape="false" :show-close="scrapeStatus !== 'loading'">
      <div class="scrape-dialog-content">
        <!-- 加载中状态 -->
        <template v-if="scrapeStatus === 'loading'">
          <div class="scrape-loading-spinner">
            <el-icon class="is-loading">
              <Refresh />
            </el-icon>
          </div>
          <div class="scrape-status-text">
            <p>正在爬取数据，请稍候...</p>
          </div>
        </template>

        <!-- 成功状态 -->
        <template v-else-if="scrapeStatus === 'success'">
          <div class="scrape-success-icon">
            <el-icon>
              <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z" fill="currentColor"/>
              </svg>
            </el-icon>
          </div>
          <div class="scrape-status-text">
            <p>爬取成功！</p>
          </div>
        </template>

        <!-- 失败状态 -->
        <template v-else-if="scrapeStatus === 'error'">
          <div class="scrape-error-icon">
            <el-icon>
              <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z" fill="currentColor"/>
              </svg>
            </el-icon>
          </div>
          <div class="scrape-status-text">
            <p class="error-title">爬取失败</p>
            <p class="error-message">{{ scrapeErrorMessage }}</p>
          </div>
        </template>
      </div>

      <!-- 对话框底部按钮 -->
      <template #footer v-if="scrapeStatus !== 'loading'">
        <div class="scrape-dialog-footer">
          <el-button type="primary" @click="scrapeDialogVisible = false">
            {{ scrapeStatus === 'success' ? '关闭' : '重试' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script setup lang="ts">
// 保留从首页返回时的筛选状态：通过 KeepAlive 缓存 Home 组件
defineOptions({ name: 'Home' })
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { changePassword, getUserInfo } from '../api/auth'
import { getMatchData, startClimb, getExponent, getMainTableCount, refreshEvents } from '../api/companies'
import { getEvents } from '../api/event'
import { Refresh } from '@element-plus/icons-vue'
type Row = {
  league: string
  midtime: string
  match: string
  score: string
  goalTime: string
  early: string
  final: string
  midHandicap: string
  overunder: string | number
  midOverunder: string | number
  mid?: string | number
}
type Filters = {
  score: string
  morning_session: string
  closing_session: string
  midfield: string
  big_small_plate: string
  mid_big_small_plate: string
}
type StatsRow = {
  category: string
  type: string
  homeOdds: string
  handicap: string
  awayOdds: string
  totalGames: number
  homeWins: number
  draws: number
  awayWins: number
  selected: boolean
}
// 是否启用后端分页
const useServerPaging = ref(true)
// 后端返回的总条数
const totalCount = ref(0)
const router = useRouter()
// 打开详情：跳转到详情页
const openDetail = (row: Row) => {
  const mid = row?.mid
  if (mid == null || mid === '') {
    ElMessage.warning('该行缺少 mid，无法查看详情')
    return
  }
  router.push({ path: `/detail/${mid}` })
}
// 添加新的详情页面跳转函数
const openDetail2 = (row: Row) => {
  const mid = row?.mid
  if (mid == null || mid === '') {
    ElMessage.warning('该行缺少 mid，无法查看详情')
    return
  }
  router.push({ path: `/detail2/${mid}` })
}
const tableData = ref<Row[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
// 页码或每页数变化时，触发后端分页加载
watch([currentPage, pageSize], () => {
  if (useServerPaging.value) loadMatchData()
})
// 修改密码相关
const changePasswordVisible = ref(false)
const changePasswordFormRef = ref<FormInstance>()
const changePasswordLoading = ref(false)
const changePasswordForm = ref({
  newPassword: '',
  confirmPassword: ''
})
const changePasswordRules: FormRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
    { max: 20, message: '密码长度不能超过20位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (_rule, value, callback) => {
        if (value !== changePasswordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 筛选器状态
const filters = ref<Filters>({
  score: '',
  morning_session: '',
  closing_session: '',
  midfield: '',
  big_small_plate: '',
  mid_big_small_plate: '',
})
// 筛选器变化处理
const handleFilterChange = () => {
  currentPage.value = 1 // 重置到第一页
  if (useServerPaging.value) loadMatchData()
}
// 添加用户信息状态
const userInfo = ref<any>(null)
// 修改密码相关函数
const openChangePasswordDialog = async () => {
  changePasswordVisible.value = true
  const response = await getUserInfo()
  userInfo.value = response.data  // 保存用户信息
  console.log('response', response)
  changePasswordForm.value = {
    newPassword: '',
    confirmPassword: ''
  }
}
const handleChangePassword = async () => {
  if (!changePasswordFormRef.value) return
  await changePasswordFormRef.value.validate(async (valid) => {
    if (valid) {
      changePasswordLoading.value = true
      try {
        console.log('userInfo', userInfo.value[0].id)
        const response = await changePassword({
          userId: userInfo.value[0].id,  // 使用保存的用户信息
          newPassword: changePasswordForm.value.newPassword
        })
        changePasswordLoading.value = false
        if (response.status === 200) {
          ElMessage.success('密码修改成功！请重新登录')
          changePasswordVisible.value = false
          // 延迟1.5秒后清除登录状态并跳转到登录页面
          setTimeout(() => {
            localStorage.removeItem('loggedIn')
            localStorage.removeItem('loginExpiration')
            router.push('/login')
          }, 1500)
        } else {
          ElMessage.error(response.data.message || '密码修改失败')
        }
      } catch (error: any) {
        changePasswordLoading.value = false
        if (error.response && error.response.status === 400) {
          ElMessage.error('当前密码错误')
        } else {
          ElMessage.error('密码修改失败，请稍后重试')
        }
      }
    } else {
      ElMessage.error('请检查输入信息')
    }
  })
}
const cancelChangePassword = () => {
  changePasswordVisible.value = false
}
// 退出登录
const handleLogout = () => {
  ElMessage.success('已退出登录')
  localStorage.removeItem('loggedIn')
  localStorage.removeItem('loginExpiration')
  router.push('/login')
}
const filteredData = computed(() => {
  let data = tableData.value
  // 比分筛选
  if (filters.value.score) {
    data = data.filter(r => r.score.includes(filters.value.score))
  }
  // 早盘筛选
  if (filters.value.morning_session) {
    data = data.filter(r => r.early.includes(filters.value.morning_session))
  }
  // 终盘筛选
  if (filters.value.closing_session) {
    data = data.filter(r => r.final.includes(filters.value.closing_session))
  }
  // 中场让球盘筛选
  if (filters.value.midfield) {
    data = data.filter(r => r.midHandicap.includes(filters.value.midfield))
  }
  // 大小盘筛选
  if (filters.value.big_small_plate) {
    data = data.filter(r => r.overunder.toString().includes(filters.value.big_small_plate))
  }
  // 中场大小盘筛选
  if (filters.value.mid_big_small_plate) {
    data = data.filter(r => r.midOverunder.toString().includes(filters.value.mid_big_small_plate))
  }
  return data
})
// 分页后的数据
const pagedData = computed(() => {
  if (useServerPaging.value) return filteredData.value
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})
// 分页事件处理（确保触发加载）
const onPageChange = (p: number) => {
  currentPage.value = p
  if (useServerPaging.value) loadMatchData()
}
const onPageSizeChange = (s: number) => {
  pageSize.value = s
  currentPage.value = 1
  if (useServerPaging.value) loadMatchData()
}
const companies = ref([
  { cid: 3, cname: 'Crow*' },
  { cid: 8, cname: '36*' },
  { cid: 12, cname: '易*' }
]);
const selectedFirstScoreId = ref(1)
const firstScore = ref([
  { id: 1, firstScore: '0:0' },
  { id: 2, firstScore: '0:1' },
  { id: 3, firstScore: '0:2' },
  { id: 4, firstScore: '0:3' },
  { id: 5, firstScore: '1:0' },
  { id: 6, firstScore: '1:1' },
  { id: 7, firstScore: '1:2' },
  { id: 8, firstScore: '1:3' },
  { id: 9, firstScore: '2:0' },
  { id: 10, firstScore: '2:1' },
  { id: 11, firstScore: '2:2' },
  { id: 12, firstScore: '2:3' },
  { id: 13, firstScore: '3:0' },
  { id: 14, firstScore: '3:1' },
])
const companiesLoading = ref(false)
const selectedCompanyId = ref(3); // 默认选中 Crow*

const scrapeLoading = ref(false)
const scrapeDialogVisible = ref(false)
const scrapeStatus = ref<'loading' | 'success' | 'error'>('loading') // 爬取状态
const scrapeErrorMessage = ref('') // 错误信息

const eventList = ref<any[]>([])
const eventsLoading = ref(false)
const selectedEventId = ref<number | null>(null)
const loadEvents = async (date?: string) => {
  eventsLoading.value = true
  try {
    // 使用传入的日期或当前选中的日期
    const queryDate = date || selectedDate.value
    let dateParam = ''

    if (queryDate) {
      // 转换日期格式 YYYY-MM-DD -> YYYYMMDD
      dateParam = queryDate.replace(/-/g, '')
    }

    // 调用 /event 获取可选比赛列表
    const resp = await getEvents(dateParam)
    const payload: any = resp?.data
    const list = Array.isArray(payload) ? payload : (payload?.data ?? [])
    eventList.value = Array.isArray(list) ? list : []
    console.log('eventList', eventList.value)

  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || e?.message || '赛事列表加载失败')
    eventList.value = []
  } finally {
    eventsLoading.value = false
  }
}
// 选择比赛时打印出所选数据
const handleEventChange = async (pid: number | null) => {
  if (pid) {
    const selected = eventList.value.find((e: any) => e?.pid === pid)
    selectedEventId.value = selected?.pid || null
    console.log('选中的比赛id：', selectedEventId.value);

    // 先重置统计数据为默认状态
    initializeStatsData()

    if (selectedEventId.value) {
      await loadStats()
      await loadMatchData()
    }
  } else {
    // 清除选择时重置为默认状态
    selectedEventId.value = null
    initializeStatsData()
    tableData.value = []
    totalCount.value = 0
    await loadMatchData()
  }
}
// 赛事数据加载与格式化
const matchesLoading = ref(false)
// 更稳健的 Unicode 解码（支持 \\uXXXX 形式，无需 JSON.parse）
const decodeUnicode = (input: any) => {
  if (input == null) return ''
  const str = String(input)
  return str.replace(/\\u([0-9a-fA-F]{4})/g, (_: string, g: string) => String.fromCharCode(parseInt(g, 16)))
}
// 高亮“受让”关键字为红色
const highlightShouRang = (text: any) => {
  const s = String(text ?? '')
  return s.replace(/受让/g, '<span class="text-red">受让</span>')
}
const mapMatchRow = (item: any): Row => {
  const league = item?.league ?? item?.league_name ?? ''
  const midtime = item?.midtime ?? item?.midtime ?? ''
  const parties = item?.parties ?? item?.match ?? ''
  const endHalf = item?.end_half ?? item?.endHalf ?? ''
  const firstHalf = item?.first_half ?? item?.firstHalf ?? ''
  const goalTime = item?.goal_time ?? item?.goalTime ?? ''
  const earlyRaw = item?.morning_session ?? item?.morningSession ?? item?.morning_seesion ?? item?.early
    ?? item?.opening_session ?? item?.opening ?? item?.open ?? item?.initial ?? ''
  const finalRaw = item?.closing_session ?? item?.closingSession ?? item?.final ?? item?.closing ?? ''
  const midHandicap = item?.midfield ?? item?.mid_handicap ?? ''
  const overunder = item?.big_small_plate ?? item?.overunder ?? ''
  const mid = item?.mid ?? item?.match_id ?? item?.id ?? item?.MID ?? item?.MatchID
  const midOverunder = item?.mid_big_small_plate ?? item?.mid_overunder ?? ''
  // 清理上半场文本外层可能已有的中/英文括号，避免重复括号
  const fhRaw = String(firstHalf || '').trim()
  const fh = fhRaw.replace(/^[（(]\s*/, '').replace(/\s*[）)]$/, '')
  return {
    league: decodeUnicode(league || ''),
    midtime: decodeUnicode(midtime || ''),
    match: decodeUnicode(parties || ''),
    score: [endHalf, fh ? `(${fh})` : ''].filter(Boolean).join(' '),
    goalTime: String(goalTime || ''),
    early: decodeUnicode(earlyRaw),
    final: decodeUnicode(finalRaw),
    midHandicap: String(midHandicap || ''),
    overunder: overunder ?? '',
    midOverunder: midOverunder ?? '',
    mid
  }
}
const normalizeMainTableList = (raw: any): Row[] => {
  const list = Array.isArray(raw) ? raw : (raw?.list ?? raw?.rows ?? raw?.data ?? [])
  if (Array.isArray(list)) return list.map(mapMatchRow)
  const maybeList = raw?.data?.list ?? raw?.data?.rows ?? []
  return Array.isArray(maybeList) ? maybeList.map(mapMatchRow) : []
}
const loadMatchData = async () => {
  console.log('当前选中的公司ID:', selectedCompanyId.value)
  matchesLoading.value = true
  try {
    const params: any = {}
    // 添加公司ID - 直接使用 selectedCompanyId.value
    if (selectedCompanyId.value != null) {
      params.cid = JSON.stringify(selectedCompanyId.value)
      console.log('发送的公司cid值:', selectedCompanyId.value)
    }
    params.pid = selectedEventId.value
    // 添加分页参数
    params.page = currentPage.value
    params.per_page = pageSize.value
    // 添加筛选条件
    if (filters.value.score) {
      params.score = filters.value.score
    }
    if (filters.value.morning_session) {
      params.morning_session = filters.value.morning_session
    }
    if (filters.value.closing_session) {
      params.closing_session = filters.value.closing_session
    }
    if (filters.value.midfield) {
      params.midfield = filters.value.midfield
    }
    if (filters.value.big_small_plate) {
      params.big_small_plate = filters.value.big_small_plate
    }
    if (filters.value.mid_big_small_plate) {
      params.mid_big_small_plate = filters.value.mid_big_small_plate
    }
    const resp = await getMatchData(params)
    const payload: any = resp?.data
    const data = payload?.data ?? payload
    tableData.value = normalizeMainTableList(data)
    // 提取总数（兼容多种返回结构）
    const totalFromResp = (payload && typeof payload.total === 'number') ? payload.total
      : (data && typeof data.total === 'number') ? data.total
        : undefined
    totalCount.value = typeof totalFromResp === 'number' ? totalFromResp : tableData.value.length
    // 同步后端返回的页码与每页数（若提供）
    if (data && typeof data.per_page === 'number') pageSize.value = data.per_page
    if (data && typeof data.page === 'number') currentPage.value = data.page
  } catch (e: any) {
    console.error('加载赛事数据失败:', e?.response || e)
    ElMessage.error(e?.response?.data?.message || e?.message || '赛事数据加载失败，请稍后重试')
    tableData.value = []
  } finally {
    matchesLoading.value = false
  }
}
const handleCompanyChange = async () => {
  if (!selectedCompanyId.value) {
    // 如果清空了公司选择
    tableData.value = []
    statsData.value = []
    initializeStatsData()
    return
  }
  initializeStatsData()
  currentPage.value = 1
  ElMessage.info('正在切换公司数据...')

  try {
    // 同时刷新统计数据和表格数据
    await Promise.all([
      loadStats(),
      loadMatchData()
    ])

    const selectedCompany = companies.value.find(c => c.cid === selectedCompanyId.value)
    ElMessage.success(`已切换到 ${selectedCompany?.cname || '所选公司'}`)
  } catch (e: any) {
    ElMessage.error('切换公司失败，请重试')
    console.error('公司切换失败:', e)
  }
}
const handleFirstScoreChange = async () => {
  if (!selectedFirstScoreId.value) {
    return
  }

  currentPage.value = 1
  const selectedScore = firstScore.value.find(item => item.id === selectedFirstScoreId.value)
  ElMessage.info(`正在加载 ${selectedScore?.firstScore} 的数据...`)

  try {
    await loadMatchData()
    ElMessage.success(`已切换到半场比分 ${selectedScore?.firstScore}`)
  } catch (e: any) {
    ElMessage.error('切换半场比分失败，请重试')
  }
}
const statsData = ref<StatsRow[]>([])
// 初始化统计数据，包含初盘和即时的默认行
const initializeStatsData = () => {
  statsData.value = [
    {
      category: '初盘',
      type: 'initial',
      selected: false,
      homeOdds: '-',
      handicap: '-',
      awayOdds: '-',
      totalGames: 0,
      homeWins: 0,
      draws: 0,
      awayWins: 0
    },
    {
      category: '即时',
      type: 'instant',
      selected: false,
      homeOdds: '-',
      handicap: '-',
      awayOdds: '-',
      totalGames: 0,
      homeWins: 0,
      draws: 0,
      awayWins: 0
    }
  ]
}
// 加载指数与总计数据（依赖所选公司与比赛）
const loadStats = async () => {
  if (!selectedCompanyId.value || !selectedEventId.value) {
    console.log('缺少必要参数:', { selectedCompanyId: selectedCompanyId.value, selectedEventId: selectedEventId.value })
    return
  }

  try {
    const [expResp, cntResp] = await Promise.all([
      getExponent(selectedCompanyId.value, selectedEventId.value), // 传递比赛ID
      getMainTableCount(selectedCompanyId.value, selectedEventId.value)
    ])

    const expPayload: any = (expResp?.data as any)?.data ?? expResp?.data
    const cntPayload: any = (cntResp?.data as any)?.data ?? cntResp?.data

    const initialTotal = Number(cntPayload?.main_count ?? 0) + Number(cntPayload?.ping_count ?? 0) + Number(cntPayload?.ke_count ?? 0)
    const instantTotal = Number(cntPayload?.main2_count ?? 0) + Number(cntPayload?.ping2_count ?? 0) + Number(cntPayload?.ke2_count ?? 0)

    statsData.value = [
      {
        category: '初盘',
        type: 'initial',
        selected: false,
        homeOdds: String(expPayload?.mteam ?? ''),
        handicap: decodeUnicode(expPayload?.dopen ?? ''),
        awayOdds: String(expPayload?.vteam ?? ''),
        totalGames: initialTotal,
        homeWins: Number(cntPayload?.main_count ?? 0),
        draws: Number(cntPayload?.ping_count ?? 0),
        awayWins: Number(cntPayload?.ke_count ?? 0)
      },
      {
        category: '即时',
        type: 'instant',
        selected: false,
        homeOdds: String(expPayload?.mteam2 ?? ''),
        handicap: decodeUnicode(expPayload?.dopen2 ?? ''),
        awayOdds: String(expPayload?.vteam2 ?? ''),
        totalGames: instantTotal,
        homeWins: Number(cntPayload?.main2_count ?? 0),
        draws: Number(cntPayload?.ping2_count ?? 0),
        awayWins: Number(cntPayload?.ke2_count ?? 0)
      }
    ]


    console.log('statsData', statsData.value)
  } catch (e: any) {
    console.error('加载指数/总计失败:', e?.response || e)
  }
}
// 添加复选框变化处理函数
const handleRowSelectionChange = (row: any) => {
  console.log(`${row.category} 选中状态:`, row.selected)
  // 这里可以添加选中状态变化的逻辑
}
// 触发爬取操作：调用 /mainTable/climbpcid，传入 cid 和 pid
const handleScrape = async () => {
  if (!selectedCompanyId.value) {
    ElMessage.warning('请先选择公司')
    return
  }
  if (!selectedEventId.value) {
    ElMessage.warning('请先选择比赛')
    return
  }
  if (!selectedFirstScoreId.value) {
    ElMessage.warning('请先选择半场比分')
    return
  }

  // 获取复选框选中状态
  const initialSelected = statsData.value.find(row => row.type === 'initial')?.selected
  const instantSelected = statsData.value.find(row => row.type === 'instant')?.selected
  if (!initialSelected && !instantSelected) {
    ElMessage.warning('请先选择初盘或即时')
    return
  }

  scrapeLoading.value = true
  scrapeDialogVisible.value = true
  scrapeStatus.value = 'loading'
  scrapeErrorMessage.value = ''

  try {
    console.log('比赛id', selectedEventId.value);
    console.log('公司id', selectedCompanyId.value);
    console.log('初盘选中:', initialSelected, '即时选中:', instantSelected);

    const requestData: any = {
      cid: selectedCompanyId.value,
      pid: selectedEventId.value,
      t1: initialSelected ? "1" : "",
      t2: instantSelected ? "2" : "",
      firstscore: firstScore.value.find(item => item.id === selectedFirstScoreId.value)?.firstScore || "0:0"
    }

    const resp = await startClimb(requestData)
    if (resp?.status === 200) {
      // 爬取完成后自动刷新统计表格和主表格
      await Promise.all([
        loadStats(),
        loadMatchData()
      ])

      // 显示成功状态
      scrapeStatus.value = 'success'
      scrapeLoading.value = false
      ElMessage.success('爬取成功，数据已更新')

      // 2秒后自动关闭对话框
      setTimeout(() => {
        scrapeDialogVisible.value = false
      }, 2000)
    } else {
      // 返回状态异常
      scrapeStatus.value = 'error'
      scrapeErrorMessage.value = '返回状态异常，请稍后重试'
      scrapeLoading.value = false
    }
  } catch (e: any) {
    // 捕获错误
    scrapeStatus.value = 'error'
    scrapeLoading.value = false
    const errorMsg = e?.response?.data?.message || e?.message || '爬取触发失败，请稍后重试'
    scrapeErrorMessage.value = errorMsg
    ElMessage.error(errorMsg)
  }
}
// 统计数据点击处理
const handleStatsClick = async (row: StatsRow, type: 'total' | 'home' | 'draw' | 'away') => {
  try {
    const params: any = {
      pid: selectedEventId.value,
      cid: selectedCompanyId.value,
      page: 1,
      per_page: 20
    }

    // 根据行类型设置 t 参数
    if (row.type === 'initial') {
      params.t = "1" // 初盘
    } else if (row.type === 'instant') {
      params.t = "2"    // 即时
    }

    // 根据点击类型设置 result 参数
    switch (type) {
      case 'total':
        // 场：不设置 result
        break
      case 'home':
        // 主：result=2
        params.result = "2"
        break
      case 'draw':
        // 和：result=1
        params.result = "1"
        break
      case 'away':
        // 客：result=0
        params.result = "0"
        break
    }

    // 添加当前选中的公司ID
    if (selectedCompanyId.value) {
      params.cid = JSON.stringify(selectedCompanyId.value)
    }

    console.log('统计筛选参数:', params)
    const resp = await getMatchData(params)

    // 使用与 loadMatchData 相同的数据处理逻辑
    if (resp?.data) {
      const payload: any = resp?.data
      const data = payload?.data ?? payload
      tableData.value = normalizeMainTableList(data)

      const typeText = type === 'total' ? '全部' : type === 'home' ? '主胜' : type === 'draw' ? '平局' : '客胜'
      const categoryText = row.type === 'initial' ? '初盘' : '即时'
      ElMessage.success(`已筛选${categoryText}${typeText}数据`)
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || e?.message || '数据筛选失败')
  }
}
// Add these reactive variables
const selectedDate = ref(new Date().toISOString().split('T')[0]) // 默认今天

const datePickerKey = ref(0)

// 禁用未来日期
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}

// 日期变化处理
const handleDateChange = async (date: string) => {
  if (date) {
    ElMessage.success(`已选择日期: ${date}`)
    // 清空当前选中的比赛
    selectedEventId.value = null
    // 根据新日期加载赛事列表
    await loadEvents(date)
  }
}

// 更新刷新赛事方法
const handleRefreshEvents = async () => {
  if (!selectedDate.value) {
    ElMessage.warning('请先选择日期')
    return
  }

  eventsLoading.value = true
  try {
    // 转换日期格式 YYYY-MM-DD -> YYYYMMDD
    const dateStr = selectedDate.value.replace(/-/g, '')

    // 调用刷新接口
    await refreshEvents({ date: dateStr })

    // 重新加载对应日期的赛事列表
    await loadEvents(selectedDate.value)

    ElMessage.success('赛事数据已刷新')
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || e?.message || '刷新赛事失败')
  } finally {
    eventsLoading.value = false
  }
}
onMounted(async () => {
  // 设置当前日期
  const today = new Date()
  const year = today.getFullYear()
  const month = String(today.getMonth() + 1).padStart(2, '0')
  const day = String(today.getDate()).padStart(2, '0')
  selectedDate.value = `${year}-${month}-${day}`

  // 初始化统计数据显示
  initializeStatsData()
  await loadEvents(selectedDate.value)
  await loadMatchData()
})
</script>
<style scoped>
/* 基础布局样式 */
.home {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
  box-sizing: border-box;
}

/* 头部样式 */
.header {
  display: flex;
  align-items: center;
  padding: 16px 0;
  margin-bottom: 20px;
  width: 100%;
  position: relative;
}

.brand {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
  margin-right: 20px;
}

.spacer {
  flex: 1;
}

.user-actions {
  margin-left: auto;
}

/* 卡片容器样式 */
.stats-table-card {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  background-color: #fff;
}

.table-header {
  display: flex;
  height: 72px;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  padding-bottom: 0px;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

/* 统计信息区域样式 */
.stats-section {
  width: 100%;
  padding: 20px;
  padding-top: 0px;
  box-sizing: border-box;
  border-bottom: 1px solid #f0f2f5;
}

.stats-table-wrapper {
  width: 100%;
  overflow-x: auto;
  /* 处理内容溢出 */
}

/* 分组表头样式 */
.group-headers {
  display: flex;
  width: 100%;
}

.group-header {
  padding: 8px 0;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.empty-header {
  width: 287px;
  /* 与左侧分类列宽度严格匹配 */
  border: 1px solid #e5e7eb;
  border-bottom: 0px;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 0 8px;
}

.scrape-controls {
  display: inline-flex;
  align-items: center;
  gap: 12px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.index-header {
  width: 500px;
  align-items: center;
  justify-content: center;
  background-color: red;
  text-align: center;
  line-height: 2;
  color: #fff;
}

.total-header {
  width: 617px;
  align-items: center;
  justify-content: center;
  background-color: #1890ff;
  text-align: center;
  line-height: 2;
  color: #fff;
}

/* 统计表格样式 - 确保铺满宽度 */
::v-deep .stats-table {
  width: 100% !important;
  table-layout: fixed;
  border-collapse: collapse;
  border-bottom: 1px solid #e5e7eb;
}

::v-deep .stats-table .el-table__cell {
  padding: 12px 0;
  text-align: center;
  border-right: 1px solid #e5e7eb;
}

::v-deep .stats-table .el-table__row:last-child .el-table__cell {
  border-bottom: none;
}

/* 主表格样式 - 强制铺满宽度 + 清除灰色线条 */
::v-deep .el-table {
  width: 100% !important;
  /* 移除 min-width: 1000px; */
  border-radius: 0;
  border-top: none;
  border: none !important;
  table-layout: fixed; /* 固定表格布局 */
}

/* 优化表格列宽分配 */
::v-deep .el-table .el-table__cell {
  padding: 8px 4px; /* 减少内边距 */
  font-size: 13px; /* 稍微减小字体 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 针对移动端进一步优化 */
@media (max-width: 1200px) {
  ::v-deep .el-table .el-table__cell {
    padding: 6px 2px;
    font-size: 12px;
  }

  /* 隐藏部分非关键列 */
  .el-table-column:nth-child(n+8) {
    display: none;
  }
}

/* 表格容器不允许横向滚动 */
.stats-table-card {
  overflow-x: hidden;
}

::v-deep .el-table__body-wrapper {
  overflow-x: hidden !important;
}

::v-deep .el-table__header-wrapper th {
  background-color: #f5f7fa;
  font-weight: 600;
  text-align: center;
  border: none !important;
  /* 清除表头单元格边框 */
}

::v-deep .el-table__body tr:hover>td {
  background-color: #f5f7fa;
}

/* 清除表格所有分隔线（关键：解决灰色线条问题） */
::v-deep .el-table--border::after,
::v-deep .el-table--group::after,
::v-deep .el-table td::before,
::v-deep .el-table th::before {
  background-color: transparent !important;
  /* 伪元素分隔线透明 */
}

::v-deep .el-table .el-table__cell {
  border-right: none !important;
  /* 清除单元格右侧边框 */
  border-bottom: none !important;
  /* 清除单元格底部边框 */
}

::v-deep .el-table__header,
::v-deep .el-table__body {
  width: 100% !important;
}

/* 分类标签样式 */
.category-label {
  padding: 6px 12px;
  border-radius: 4px;
  color: #fff;
  font-weight: 500;
  display: inline-block;
}

.category-label.initial {
  width: 100%;
  background-color: #409eff;
}

.category-label.instant {
  width: 100%;
  background-color: #67c23a;
}

/* 表头筛选器样式 */
.header-with-filter {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.header-title {
  margin-bottom: 4px;
  font-weight: 600;
}

::v-deep .el-select {
  margin-right: 8px;
}

/* 分页样式 */
.pager {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  /* border-top: 1px solid #e5e7eb; */
  margin-top: 0;
}

.total {
  color: #666;
  font-size: 14px;
}

::v-deep .el-pagination {
  margin: 0;
}

/* 对话框样式 */
::v-deep .el-dialog__body {
  padding: 20px;
}

::v-deep .dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

/* 头像和下拉菜单样式 */
::v-deep .el-avatar {
  cursor: pointer;
  transition: transform 0.2s;
}

::v-deep .el-avatar:hover {
  transform: scale(1.05);
}

::v-deep .el-dropdown-menu {
  min-width: 120px;
}

/* 链接样式 */
::v-deep .el-link {
  color: #1890ff;
}

::v-deep .el-link:hover {
  color: #409eff;
}

/* 红色高亮样式（受让关键字） */
.text-red {
  color: red;
}

/* 表头悬停效果 */
::v-deep .el-table__header-wrapper th {
  color: rgb(57, 57, 57);
  font-weight: bolder;
}

.is-selected {
  color: #1989fa;
  font-weight: bold;
}

.dialog-footer {
  text-align: right;
}

.el-calendar {
  --el-calendar-selected-bg-color: #f0f9ff;
  --el-calendar-cell-width: 85px;
}

/* 可点击单元格样式 - 适配平板 */
.clickable-cell {
  color: #409eff;
  cursor: pointer;
  padding: 12px 8px;
  min-height: 44px; /* 符合移动端最小点击区域标准 */
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: background-color 0.2s;
  user-select: none;
}

.clickable-cell:hover {
  background-color: #ecf5ff;
  color: #337ecc;
}

.clickable-cell:active {
  background-color: #d9ecff;
  transform: scale(0.98);
}

/* 平板和移动端优化 */
@media (max-width: 1024px) {
  .clickable-cell {
    padding: 16px 12px;
    min-height: 48px;
    font-size: 16px;
  }
}

/* 爬取对话框样式 */
.scrape-dialog-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px 10px;
  text-align: center;
}

.scrape-loading-spinner {
  margin-bottom: 20px;
}

::v-deep .scrape-loading-spinner .el-icon {
  font-size: 48px;
  color: #409eff;
  animation: spin 2s linear infinite;
}

.scrape-success-icon {
  margin-bottom: 20px;
}

::v-deep .scrape-success-icon .el-icon {
  font-size: 48px;
  color: #67c23a;
}

.scrape-error-icon {
  margin-bottom: 20px;
}

::v-deep .scrape-error-icon .el-icon {
  font-size: 48px;
  color: #f56c6c;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.scrape-status-text {
  font-size: 16px;
  color: #333;
}

.scrape-status-text p {
  margin: 0;
  font-weight: 500;
}

.scrape-status-text .error-title {
  color: #f56c6c;
  font-size: 16px;
  margin-bottom: 8px;
}

.scrape-status-text .error-message {
  color: #909399;
  font-size: 14px;
  margin-top: 8px;
  word-break: break-word;
  max-height: 100px;
  overflow-y: auto;
}

.scrape-dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}
</style>
